import React, { useState, useEffect, useRef, useCallback } from 'react';
import applePayIcon from '@/assets/images/applepay.png'
import { loadStripe } from '@stripe/stripe-js';
import useIsMobile from '@/hooks/isMoboile';
import { request } from '@/api/request';
import CryptoJS from 'crypto-js';

import {
    Elements,
    CardElement,
    PaymentRequestButtonElement,
    useStripe,
    useElements
} from '@stripe/react-stripe-js';
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom';

// 定义用户信息解密的函数 - 从Settings组件借用
const decryptData = (encrypted: any) => {
    try {
        const key = CryptoJS.enc.Utf8.parse('yydskno1me888888');
        const decrypted = CryptoJS.AES.decrypt(encrypted, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7,
        });
        const decryptedStr = CryptoJS.enc.Utf8.stringify(decrypted);
        // 将解密后的字符串转换为JSON对象
        return JSON.parse(decryptedStr);
    } catch (error) {
        console.error('decrypt or parse JSON failed', error);
        return null;
    }
};

// 初始化Stripe - 使用正式环境的发布密钥
const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || 'pk_live_51ROwEEChGeSzAdpVPI0xje3ec38B9WC91iWSSJ0A14htWSermOZPM8LVk70vYTA11qWoTVehdOZbB5Wc01gSlVLn00KWSMEwTJ'); //正式
// const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || 'pk_test_51ROwErEHIcYxLscxoZCrV13WZVNuEU50I6Luq6YVSUSDBSGe4XANVSB6DiGqjyZcLzQef5QMHmNxuYl468WuCUC400qPb7pPMY'); //测试

// 支付数据接口定义 - 支持订阅和一次性支付
interface PaymentData {
    clientSecret: string;
    amount: number;
    currency: string;
    // 可选的标识字段
    order_id?: string;
    stripe_price_id?: string;
    // 订阅支付字段
    subscriptionId?: string;
    customerId?: string;
    paymentIntentId?: string;
    invoiceId?: string;
    message?: string;
    // 可选的计划信息
    selectedPlan?: string;
}

// 支付方式类型定义
interface PaymentMethod {
    type: 'applePay' | 'googlePay' | 'link';
    available: boolean;
    ready: boolean;
    paymentRequest?: any;
}

// 多支付方式按钮组件 - 支持Apple Pay、Google Pay和Link支付
const MultiPaymentButtons: React.FC<{
    paymentData: PaymentData;
    onPaymentSuccess: () => void;
    onPaymentError: (error: string) => void;
}> = ({ paymentData, onPaymentSuccess, onPaymentError }) => {
    const stripe = useStripe();
    const { t } = useTranslation();
    const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const isMobile = useIsMobile();

    useEffect(() => {
        if (!stripe) return;

        const initializePaymentMethods = async () => {
            try {
                // 创建统一的PaymentRequest来支持所有支付方式
                const unifiedPaymentRequest = stripe.paymentRequest({
                    country: 'US',
                    currency: paymentData.currency.toLowerCase(),
                    total: {
                        label: paymentData.subscriptionId ?
                            (paymentData.selectedPlan === 'yearly' ? t('PayMoney.yearlySubscription', { defaultValue: 'Yearly Subscription' }) : t('PayMoney.monthlySubscription', { defaultValue: 'Monthly Subscription' })) :
                            t('PayMoney.oneTimePayment', { defaultValue: 'One-time Payment' }),
                        amount: paymentData.amount,
                    },
                    requestPayerName: true,
                    requestPayerEmail: true,
                    // 不禁用任何钱包，让所有支持的方式都可用
                });

                // 检测可用的支付方式
                const canMakePayment = await unifiedPaymentRequest.canMakePayment();
                const methods: PaymentMethod[] = [];

                if (canMakePayment) {
                    // 设置统一的事件监听
                    unifiedPaymentRequest.on('paymentmethod', handlePaymentMethod);

                    // Apple Pay
                    if (canMakePayment.applePay) {
                        // 检查原生Apple Pay支持
                        const hasNativeApplePay = (window as any).ApplePaySession && (window as any).ApplePaySession.canMakePayments();

                        // console.log('Apple Pay is available:', { hasNativeApplePay, canMakePayment: canMakePayment.applePay });

                        methods.push({
                            type: 'applePay',
                            available: true,
                            ready: true,
                            paymentRequest: unifiedPaymentRequest // 使用统一的PaymentRequest
                        });
                    }

                    // Google Pay
                    if (canMakePayment.googlePay) {
                        // console.log('Google Pay is available');

                        methods.push({
                            type: 'googlePay',
                            available: true,
                            ready: true,
                            paymentRequest: unifiedPaymentRequest // 使用统一的PaymentRequest
                        });
                    }

                    // Link Pay
                    if (canMakePayment.link) {
                        // console.log('Link Pay is available');

                        methods.push({
                            type: 'link',
                            available: true,
                            ready: true,
                            paymentRequest: unifiedPaymentRequest // 使用统一的PaymentRequest
                        });
                    }
                }

                // 根据设备类型添加未设置的支付方式（显示设置引导）
                const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);

                // iOS设备优先显示Apple Pay引导（仅限移动设备）
                if (isMobile && isIOS && !methods.find(m => m.type === 'applePay')) {
                    methods.push({
                        type: 'applePay',
                        available: true,
                        ready: false,
                    });
                }

                // 所有设备（包括PC端）都显示Google Pay引导
                if (!methods.find(m => m.type === 'googlePay')) {
                    methods.push({
                        type: 'googlePay',
                        available: true,
                        ready: false,
                    });
                }

                setPaymentMethods(methods);
            } catch (error) {
                console.error('Payment methods initialization error:', error);
                // 降级：在所有设备上至少显示Google Pay引导
                setPaymentMethods([{
                    type: 'googlePay',
                    available: true,
                    ready: false,
                }]);
            } finally {
                setIsLoading(false);
            }
        };

        initializePaymentMethods();
    }, [stripe, paymentData, isMobile, t]);

    // 处理支付方法事件
    const handlePaymentMethod = async (event: any) => {
        try {
            const { error, paymentIntent } = await stripe!.confirmCardPayment(
                paymentData.clientSecret,
                { payment_method: event.paymentMethod.id }
            );

            if (error) {
                event.complete('fail');
                onPaymentError(error.message || t('PayMoney.paymentFailed'));
            } else {
                event.complete('success');
                if (paymentIntent.status === 'succeeded') {
                    // 打印快速支付成功数据
                    console.log('快速支付成功返回数据:', {
                        paymentIntent,
                        paymentData,
                        paymentMethod: event.paymentMethod
                    });
                    console.log('快速支付调用onPaymentSuccess，将触发handleGlobalPaymentSuccess');
                    onPaymentSuccess();
                } else if (paymentIntent.status === 'requires_action') {
                    // 处理需要额外验证的情况
                    const { error: confirmError } = await stripe!.confirmCardPayment(paymentData.clientSecret);
                    if (confirmError) {
                        onPaymentError(confirmError.message || t('PayMoney.authFailed'));
                    } else {
                        // 打印额外认证后支付成功数据
                        console.log('额外认证后支付成功数据:', {
                            paymentData,
                            authenticatedPayment: true
                        });
                        console.log('额外认证后支付成功，调用onPaymentSuccess，将触发handleGlobalPaymentSuccess');
                        onPaymentSuccess();
                    }
                }
            }
        } catch (err) {
            event.complete('fail');
            onPaymentError(t('PayMoney.paymentError'));
        }
    };

    // 处理设置支付方式的引导
    const handleSetupPayment = (type: 'applePay' | 'googlePay') => {
        if (type === 'applePay') {
            alert(t('PayMoney.applePaySetup', {
                defaultValue: 'Please add a payment method in iOS Settings > Wallet & Apple Pay, then refresh this page'
            }));
        } else if (type === 'googlePay') {
            window.open('https://pay.google.com/gp/w/home/signup', '_blank', 'noopener,noreferrer');
        }
    };

    if (isLoading) {
        return (
            <div className="mb-4 p-4 bg-gray-800 rounded-lg text-center">
                <div className="text-gray-400 text-sm flex items-center justify-center">
                    <svg className="animate-spin -ml-1 mr-3 h-4 w-4 text-gray-400" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    {t('PayMoney.quickPayChecking', { defaultValue: 'Checking quick payment methods...' })}
                </div>
            </div>
        );
    }

    if (paymentMethods.length === 0) {
        return (
            <div className="mb-4 p-3 bg-gray-800 rounded-lg">
                <div className="text-gray-400 text-sm text-center mb-2">
                    {t('PayMoney.quickPayUnavailable', { defaultValue: 'Quick payment unavailable' })}
                </div>
                <div className="text-xs text-gray-500 text-center">
                    {t('PayMoney.useCardBelow', { defaultValue: 'Please use the credit card payment below' })}
                </div>
            </div>
        );
    }

    // 获取可用的统一PaymentRequest
    const unifiedPaymentRequest = paymentMethods.find(m => m.paymentRequest)?.paymentRequest;

    // 触发特定支付方式
    const handleSpecificPayment = async (paymentType: 'applePay' | 'googlePay' | 'link') => {
        if (!unifiedPaymentRequest) return;

        try {
            // 直接调用PaymentRequest的show方法
            const paymentResponse = await unifiedPaymentRequest.show();

            // 这里会触发paymentmethod事件，由handlePaymentMethod处理
            // console.log('Payment initiated for:', paymentType);
        } catch (error: any) {
            if (error.message && error.message.includes('canceled')) {
                // console.log('Payment canceled by user');
            } else {
                console.error('Payment error:', error);
                onPaymentError(t('PayMoney.paymentError', { defaultValue: 'An error occurred during the payment process' }));
            }
        }
    };

    return (
        <div className="mb-4 space-y-3">
            {/* 为每种支付方式创建独立的按钮 */}
            {paymentMethods.map((method) => (
                <div key={method.type} className="bg-gray-800 rounded-lg p-3">
                    {method.type === 'applePay' && (
                        <div>
                            <div className="flex items-center justify-between mb-3">
                                <div className="flex items-center">
                                    <img className="w-16 h-10" src={applePayIcon} alt="Apple Pay" />
                                </div>
                                <div className="text-xs text-green-400">
                                    {t('PayMoney.available', { defaultValue: 'Available' })}
                                </div>
                            </div>
                            {method.ready && method.paymentRequest ? (
                                <button
                                    onClick={() => handleSpecificPayment('applePay')}
                                    className="w-full bg-black hover:bg-gray-900 text-white py-3 px-4 rounded-lg transition-colors flex items-center justify-center border"
                                >
                                    <img className="w-12 h-7 mr-2" src={applePayIcon} alt="Apple Pay" />
                                    <span>{t('PayMoney.payWithApplePay', { defaultValue: 'Pay with Apple Pay' })}</span>
                                </button>
                            ) : (
                                <button
                                    onClick={() => handleSetupPayment('applePay')}
                                    className="w-full bg-gray-700 hover:bg-gray-600 text-white py-3 px-4 rounded-lg transition-colors border-2 border-dashed border-gray-500"
                                >
                                    <div className="flex items-center justify-center">
                                        <span className="mr-2">⚡</span>
                                        {t('PayMoney.setupApplePay', { defaultValue: 'Set up Apple Pay' })}
                                    </div>
                                </button>
                            )}
                        </div>
                    )}

                    {method.type === 'googlePay' && (
                        <div>
                            <div className="flex items-center justify-between mb-3">
                                <div className="text-sm text-gray-300 flex items-center">
                                    <svg className="w-4 h-4 ml-1 mr-1" viewBox="0 0 24 24" fill="none">
                                        <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
                                        <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
                                        <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
                                        <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
                                    </svg>
                                    <span className="font-semibold text-white">{t('PayMoney.googlePay', { defaultValue: 'Google Pay' })}</span>
                                </div>
                                <div className="text-xs text-green-400">
                                    {t('PayMoney.available', { defaultValue: 'Available' })}
                                </div>
                            </div>
                            {method.ready && method.paymentRequest ? (
                                <button
                                    onClick={() => handleSpecificPayment('googlePay')}
                                    className="w-full text-white py-3 px-4 rounded-lg transition-all duration-200 relative overflow-hidden group shadow-lg hover:shadow-xl"
                                    style={{
                                        background: 'linear-gradient(135deg, #4285F4 0%, #34A853 25%, #FBBC05 50%, #EA4335 75%)'
                                    }}
                                >
                                    <div className="absolute inset-0 bg-white opacity-0 group-hover:opacity-10 transition-opacity duration-200"></div>
                                    <div className="flex items-center justify-center relative z-10">
                                        <div className="w-7 h-7 mr-3 bg-white rounded-full flex items-center justify-center shadow-sm">
                                            <svg className="w-4 h-4" viewBox="0 0 24 24">
                                                <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
                                                <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
                                                <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
                                                <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
                                            </svg>
                                        </div>
                                        <span className="font-semibold">{t('PayMoney.payWithGooglePay', { defaultValue: 'Pay with Google Pay' })}</span>
                                    </div>
                                </button>
                            ) : (
                                <button
                                    onClick={() => handleSetupPayment('googlePay')}
                                    className="w-full text-white py-3 px-4 rounded-lg transition-all duration-200 relative overflow-hidden group shadow-lg hover:shadow-xl"
                                    style={{
                                        background: 'linear-gradient(135deg, #4285F4 0%, #34A853 25%, #FBBC05 50%, #EA4335 75%)'
                                    }}
                                >
                                    <div className="absolute inset-0 bg-white opacity-0 group-hover:opacity-10 transition-opacity duration-200"></div>
                                    <div className="flex items-center justify-center relative z-10">
                                        <div className="w-7 h-7 mr-3 bg-white rounded-full flex items-center justify-center shadow-sm">
                                            <svg className="w-4 h-4" viewBox="0 0 24 24">
                                                <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" />
                                                <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
                                                <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
                                                <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
                                            </svg>
                                        </div>
                                        <span className="font-semibold">{t('PayMoney.setupGooglePay', { defaultValue: 'Set up Google Pay' })}</span>
                                    </div>
                                </button>
                            )}
                        </div>
                    )}

                    {method.type === 'link' && (
                        <div>
                            <div className="flex items-center justify-between mb-3">
                                <div className="text-sm text-gray-300 flex items-center">
                                    🔗 {t('PayMoney.link', { defaultValue: 'Link' })}
                                </div>
                                <div className="text-xs text-green-400">
                                    {t('PayMoney.available', { defaultValue: 'Available' })}
                                </div>
                            </div>
                            {method.ready && method.paymentRequest && (
                                <button
                                    onClick={() => handleSpecificPayment('link')}
                                    className="w-full bg-purple-600 hover:bg-purple-700 text-white py-3 px-4 rounded-lg transition-colors flex items-center justify-center"
                                >
                                    <span className="mr-2">🔗</span>
                                    <span>{t('PayMoney.payWithLink', { defaultValue: 'Pay with Link' })}</span>
                                </button>
                            )}
                        </div>
                    )}
                </div>
            ))}

            {/* 隐藏的PaymentRequestButtonElement用于实际支付处理 */}
            {unifiedPaymentRequest && (
                <div style={{ display: 'none' }}>
                    <PaymentRequestButtonElement
                        options={{
                            paymentRequest: unifiedPaymentRequest,
                            style: {
                                paymentRequestButton: {
                                    type: 'default',
                                    theme: 'dark',
                                    height: '48px',
                                },
                            },
                        }}
                        className="PaymentRequestButton"
                    />
                </div>
            )}
        </div>
    );
};

// 全局函数：处理支付成功后的页面刷新
const handleGlobalPaymentSuccess = async () => {
    console.log('支付成功，准备更新用户数据...');

    // 定义刷新页面的函数
    const refreshPage = () => {
        console.log('更新完成，即将刷新页面...');
        window.location.href = '/';
    };

    try {
        const userDataStr = localStorage.getItem('userData');
        if (!userDataStr) {
            console.error('未找到用户数据，直接刷新页面');
            refreshPage();
            return;
        }

        const userData = JSON.parse(userDataStr);

        // 第一步：根据支付套餐立即更新前端数据，确保用户体验
        console.log('=== 第一步：立即更新前端数据 ===');

        // 获取支付数据以确定目标会员等级
        const paymentDataStr = sessionStorage.getItem('paymentData');
        let targetVipLevel = userData.vip_live; // 默认保持原有等级
        let expectedTokens = userData.tokens_balance; // 默认保持原有余额

        if (paymentDataStr) {
            try {
                const paymentData = JSON.parse(paymentDataStr);
                console.log('支付数据:', paymentData);

                // 根据支付计划确定目标VIP等级
                if (paymentData.selectedPlan) {
                    switch (paymentData.selectedPlan) {
                        case 'prelude':
                            targetVipLevel = 1;
                            expectedTokens = userData.tokens_balance + 1000; // 假设充值1000token
                            break;
                        case 'affinity':
                            targetVipLevel = 2;
                            expectedTokens = userData.tokens_balance + 3000; // 假设充值3000token
                            break;
                        case 'soulmate':
                            targetVipLevel = 3;
                            expectedTokens = userData.tokens_balance + 10000; // 假设充值10000token
                            break;
                    }
                    console.log(`根据套餐 ${paymentData.selectedPlan} 确定目标VIP等级: ${targetVipLevel}`);
                }
            } catch (e) {
                console.error('解析支付数据失败:', e);
            }
        }

        // 立即更新localStorage中的用户数据
        const immediateUpdatedData = {
            ...userData,
            vip_live: targetVipLevel,
            tokens_balance: expectedTokens
        };

        console.log('立即更新前端数据:', {
            '原vip_live': userData.vip_live,
            '新vip_live': targetVipLevel,
            '原tokens_balance': userData.tokens_balance,
            '新tokens_balance': expectedTokens
        });

        localStorage.setItem('userData', JSON.stringify(immediateUpdatedData));

        // 立即触发UI更新事件
        console.log('立即触发UI更新事件...');
        window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));

        // 立即刷新Token余额UI
        try {
            const { refreshTokenBalance } = await import('@/components/TokenBalance');
            refreshTokenBalance(expectedTokens);
            console.log('Token余额UI已立即更新');
        } catch (e) {
            console.error('立即刷新余额UI失败:', e);
        }

        // 再次触发事件确保所有组件都收到
        setTimeout(() => {
            console.log('再次触发userLoginStatusChanged事件确保所有组件更新');
            window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));
        }, 100);

        console.log('=== 第二步：异步验证API数据 ===');

        // 第二步：异步从API获取真实数据进行校验和最终更新
        const verifyDataFromAPI = async () => {
            const maxRetries = 5;
            const delay = 2000;

            for (let attempt = 1; attempt <= maxRetries; attempt++) {
                try {
                    console.log(`第${attempt}次尝试从API获取真实数据...`);

                    const res = await request.get('/api/visitor/getUserInformation', {
                        params: {
                            fields: 'avatar, displayName,gender, email, phone,membershipTier, tokensBalance',
                        }
                    });

                    if (res.data.success === true) {
                        const decryptedData = decryptData(res.data.data.encryptedData);
                        console.log(`第${attempt}次API返回数据:`, decryptedData);

                        if (decryptedData) {
                            // 检查API数据是否与预期一致
                            const apiVipLevel = decryptedData.membershipTier;
                            const apiTokens = parseFloat(decryptedData.tokensBalance);

                            console.log('API数据对比:', {
                                '预期VIP等级': targetVipLevel,
                                'API VIP等级': apiVipLevel,
                                '预期Token': expectedTokens,
                                'API Token': apiTokens
                            });

                            // 如果API数据与预期一致，或者已经是最后一次尝试，就使用API数据
                            if (apiVipLevel === targetVipLevel || attempt === maxRetries) {
                                const finalUserData = {
                                    ...userData,
                                    user_avatar: decryptedData.avatar || userData.user_avatar,
                                    user_displayName: decryptedData.displayName || userData.user_displayName,
                                    vip_live: apiVipLevel !== null && apiVipLevel !== undefined ? apiVipLevel : targetVipLevel,
                                    tokens_balance: apiTokens || expectedTokens
                                };

                                console.log('最终用户数据:', finalUserData);
                                localStorage.setItem('userData', JSON.stringify(finalUserData));

                                // 最终触发UI更新
                                window.dispatchEvent(new CustomEvent('userLoginStatusChanged'));

                                try {
                                    const { refreshTokenBalance } = await import('@/components/TokenBalance');
                                    refreshTokenBalance(finalUserData.tokens_balance);
                                } catch (e) { }

                                console.log('API数据验证完成，所有数据已最终更新');
                                return true;
                            } else {
                                console.log(`API数据还未同步，等待${delay}ms后重试...`);
                                await new Promise(resolve => setTimeout(resolve, delay));
                            }
                        }
                    } else {
                        console.error(`第${attempt}次API调用失败:`, res.data);
                        if (attempt < maxRetries) {
                            await new Promise(resolve => setTimeout(resolve, delay));
                        }
                    }
                } catch (apiError) {
                    console.error(`第${attempt}次API调用出错:`, apiError);
                    if (attempt < maxRetries) {
                        await new Promise(resolve => setTimeout(resolve, delay));
                    }
                }
            }

            console.log('API验证超时，但前端数据已更新，用户体验不受影响');
            return false;
        };

        // 异步执行API验证，不阻塞页面刷新
        verifyDataFromAPI().finally(() => {
            console.log('数据验证流程完成');
        });

        // 清除支付数据
        sessionStorage.removeItem('paymentData');

        // 等待一段时间让用户看到更新效果，然后刷新页面
        console.log('=== 等待1秒后刷新页面，让用户看到VIP状态变化 ===');
        setTimeout(() => {
            console.log('准备刷新页面，用户已看到VIP状态更新');
            refreshPage();
        }, 1000);

    } catch (e) {
        console.error('支付成功后处理用户数据失败:', e);
        // 发生错误时，也需要刷新页面
        setTimeout(refreshPage, 1000);
    }
};

// 支付表单组件 - 处理银行卡支付和快捷支付
const PaymentForm: React.FC<{ paymentData: PaymentData }> = ({ paymentData }) => {
    const stripe = useStripe();
    const elements = useElements();
    const navigate = useNavigate();
    const [isProcessing, setIsProcessing] = useState(false);
    const [paymentError, setPaymentError] = useState<string | null>(null);
    const [paymentSuccess, setPaymentSuccess] = useState(false);
    const { t } = useTranslation();

    // 处理支付成功
    const handlePaymentSuccess = () => {
        console.log('PaymentForm: 支付成功，设置成功状态并调用handleGlobalPaymentSuccess');
        setPaymentSuccess(true);

        // 使用全局函数处理支付成功后的页面刷新
        handleGlobalPaymentSuccess();
    };

    // 处理支付错误
    const handlePaymentError = (error: string) => {
        setPaymentError(error);
    };

    // 处理银行卡提交
    const handleCardSubmit = async (event: React.FormEvent) => {
        event.preventDefault();

        if (!stripe || !elements) {
            setPaymentError(t('PayMoney.loading', { defaultValue: 'Payment system loading...' }));
            return;
        }

        const card = elements.getElement(CardElement);
        if (!card) {
            setPaymentError(t('PayMoney.cardInfo', { defaultValue: 'Please enter card information' }));
            return;
        }

        setIsProcessing(true);
        setPaymentError(null);

        try {
            const { error, paymentIntent } = await stripe.confirmCardPayment(
                paymentData.clientSecret,
                {
                    payment_method: {
                        card: card
                    }
                }
            );

            if (error) {
                let errorMessage = t('PayMoney.paymentFailed', { defaultValue: 'Payment failed' });

                // 处理不同类型的错误
                switch (error.type) {
                    case 'card_error':
                        errorMessage = error.message || t('PayMoney.cardError', { defaultValue: 'Card information is incorrect, please check and try again' });
                        break;
                    case 'validation_error':
                        errorMessage = error.message || t('PayMoney.validationError', { defaultValue: 'Please check if the information entered is correct' });
                        break;
                    default:
                        errorMessage = error.message || t('PayMoney.defaultError', { defaultValue: 'An error occurred during payment, please try again later' });
                }

                setPaymentError(errorMessage);
                console.error('Payment failed:', error);
            } else if (paymentIntent && paymentIntent.status === 'succeeded') {
                // 打印支付成功数据
                console.log('银行卡支付成功返回数据:', {
                    paymentIntent,
                    paymentData
                });
                console.log('银行卡支付成功，调用handlePaymentSuccess，将触发handleGlobalPaymentSuccess');
                handlePaymentSuccess();
            }
        } catch (err) {
            console.error('Payment error:', err);
            setPaymentError(t('PayMoney.networkError', { defaultValue: 'A network error occurred during payment, please check your connection and try again' }));
        } finally {
            setIsProcessing(false);
        }
    };

    if (paymentSuccess) {
        return (
            <div className="text-center py-8">
                <div className="text-green-500 text-4xl mb-4">✓</div>
                <h2 className="text-2xl font-semibold text-white mb-2">{t('PayMoney.success', { defaultValue: 'Payment Successful!' })}</h2>
                <p className="text-gray-400 mb-4">{t('PayMoney.successDesc', { defaultValue: 'Thank you for your payment. Your service is now active' })}</p>
                <div className="text-sm text-gray-500">{t('PayMoney.redirectHome', { defaultValue: 'Redirecting to homepage...' })}</div>
            </div>
        );
    }

    // 格式化计划显示名称
    const getPlanDisplayName = (plan?: string) => {
        if (!plan) return t('PayMoney.oneTimePayment', { defaultValue: 'One-time Payment' });

        // 检查是否是产品名称映射
        const productNameKey = `PayMoney.productNames.${plan}`;
        const translatedProductName = t(productNameKey, { defaultValue: plan });

        // 如果翻译键存在且不是默认值，使用翻译
        if (translatedProductName !== plan) {
            return translatedProductName;
        }

        // 回退到原有的计划类型处理
        switch (plan) {
            case 'monthly':
                return t('PayMoney.monthly', { defaultValue: 'Monthly Subscription' });
            case 'yearly':
                return t('PayMoney.yearly', { defaultValue: 'Yearly Subscription' });
            default:
                return plan;
        }
    };

    return (
        <div className="max-w-md mx-auto">
            <div className="mb-6">
                <div className="bg-gray-800 p-4 rounded-lg mb-4">
                    <div className="flex justify-between items-center mb-2">
                        <span className="text-gray-400">
                            {paymentData.subscriptionId ? t('PayMoney.subscriptionPlan', { defaultValue: 'Subscription Plan' }) : t('PayMoney.paymentType', { defaultValue: 'Payment Type' })}
                        </span>
                        {/* 产品名称 - 已国际化 */}
                        <span className="text-white">{getPlanDisplayName(paymentData.selectedPlan)}</span>
                    </div>
                    <div className="flex justify-between items-center">
                        <span className="text-gray-400">{t('PayMoney.amount', { defaultValue: 'Amount' })}</span>
                        <span className="text-white font-semibold">
                            ￥{(paymentData.amount).toFixed(2)} {paymentData.currency.toUpperCase()}
                        </span>
                    </div>
                    {paymentData.subscriptionId && (
                        <div className="mt-2 text-xs text-blue-400">
                            {t('PayMoney.subscriptionInfo', { defaultValue: 'Subscription will auto-renew, cancel anytime' })}
                        </div>
                    )}
                </div>
            </div>

            {/* 多支付方式按钮 */}
            <MultiPaymentButtons
                paymentData={paymentData}
                onPaymentSuccess={handlePaymentSuccess}
                onPaymentError={handlePaymentError}
            />

            {/* 分隔线 */}
            <div className="flex items-center my-6">
                <div className="flex-1 border-t border-gray-600"></div>
                <span className="px-4 text-gray-400 text-sm">{t('PayMoney.orUseCard', { defaultValue: 'or use card' })}</span>
                <div className="flex-1 border-t border-gray-600"></div>
            </div>

            {/* 信用卡支付表单 */}
            <form onSubmit={handleCardSubmit}>
                <div className="mb-6">
                    <h3 className="text-white text-lg font-medium mb-4">{t('PayMoney.cardPayment', { defaultValue: 'Card Payment' })}</h3>
                </div>

                <div className="mb-6">
                    <label className="block text-white text-sm font-medium mb-2">
                        {t('PayMoney.cardInfo', { defaultValue: 'Card Information' })}
                    </label>
                    <div className="bg-white p-3 rounded border">
                        <CardElement
                            options={{
                                style: {
                                    base: {
                                        fontSize: '16px',
                                        color: '#424770',
                                        '::placeholder': {
                                            color: '#aab7c4',
                                        },
                                    },
                                    invalid: {
                                        color: '#9e2146',
                                    },
                                },
                            }}
                        />
                    </div>
                    <div className="mt-2 text-[1rem] text-gray-400">
                        {t('PayMoney.cardSupport', { defaultValue: 'Supports Visa, Mastercard, American Express and other major cards' })}
                    </div>
                </div>

                {paymentError && (
                    <div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
                        <div className="flex items-center">
                            <svg className="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
                                <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
                            </svg>
                            {paymentError}
                        </div>
                    </div>
                )}

                <button
                    type="submit"
                    disabled={!stripe || isProcessing}
                    className={`w-full py-3 px-4 rounded-lg font-medium transition-all duration-200 ${isProcessing
                        ? 'bg-gray-600 cursor-not-allowed'
                        : 'bg-blue-600 hover:bg-blue-700 shadow-lg hover:shadow-xl'
                        } text-white`}
                >
                    <div className="flex items-center justify-center">
                        {isProcessing && (
                            <svg className="animate-spin -ml-1 mr-3 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                        )}
                        {isProcessing ?
                            t('PayMoney.paying', { defaultValue: 'Processing...' }) :
                            t('PayMoney.payWithCard', {
                                defaultValue: 'Pay ￥{{amount}}',
                                amount: (paymentData.amount).toFixed(2)
                            })
                        }
                    </div>
                </button>

                <div className="mt-4 text-center">
                    <button
                        type="button"
                        onClick={() => navigate(-1)}
                        className="text-gray-400 hover:text-white transition-colors"
                    >
                        {t('PayMoney.backToSubscribe', { defaultValue: 'Back to Subscription Page' })}
                    </button>
                </div>

                {/* 安全提示 */}
                <div className="mt-4 text-center text-xs text-gray-500">
                    {t('PayMoney.secureTip', { defaultValue: '🔒 Your payment information is protected by SSL encryption' })}
                </div>
            </form>
        </div>
    );
};

// 主支付页面组件 - 整合所有支付功能
const PayMoney: React.FC = () => {
    const [paymentData, setPaymentData] = useState<PaymentData | null>(null);
    const [loading, setLoading] = useState(true);
    const navigate = useNavigate();
    const { t } = useTranslation();
    const isMobile = useIsMobile();

    // 获取支付数据
    useEffect(() => {
        // 从sessionStorage获取支付数据
        const storedPaymentData = sessionStorage.getItem('paymentData');
        if (storedPaymentData) {
            try {
                const data = JSON.parse(storedPaymentData);
                // 验证必要字段
                if (data.clientSecret && data.amount && data.currency) {
                    setPaymentData(data);
                } else {
                    console.error('Payment data missing required fields:', data);
                    navigate('/subscriptions');
                }
            } catch (error) {
                console.error(t('PayMoney.parseError', { defaultValue: 'Failed to parse payment data:' }), error);
                navigate('/subscriptions');
            }
        } else {
            // 如果没有支付数据，重定向到订阅页面
            navigate('/subscriptions');
        }
        setLoading(false);
    }, [navigate, t]);

    if (loading) {
        return (
            <div className="min-h-screen bg-gray-900 text-white flex items-center justify-center">
                <div className="text-center">
                    <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-500 mx-auto mb-4"></div>
                    <p className="text-gray-400">{t('PayMoney.loading', { defaultValue: 'Loading...' })}</p>
                </div>
            </div>
        );
    }

    if (!paymentData) {
        return (
            <div className="min-h-screen bg-gray-900 text-white flex items-center justify-center">
                <div className="text-center">
                    <h2 className="text-2xl font-semibold mb-4">{t('PayMoney.notFound', { defaultValue: 'Payment information not found' })}</h2>
                    <button
                        onClick={() => navigate('/subscriptions')}
                        className="bg-blue-600 hover:bg-blue-700 px-6 py-2 rounded-lg transition-colors"
                    >
                        {t('PayMoney.backToSubscribe', { defaultValue: 'Back to Subscription Page' })}
                    </button>
                </div>
            </div>
        );
    }

    return (
        // 最外层的盒子 
        <div className="min-h-screen bg-r-900 text-white">
            <div className="max-w-4xl mx-auto w-full px-4 sm:px-6 lg:px-8">
                <div className="text-center mb-8 pt-8">
                    <h1 className="text-3xl font-bold text-white mb-2">
                        {t('PayMoney.safePay', { defaultValue: 'Secure Payment' })}
                    </h1>
                    <p className="text-gray-400">
                        {t('PayMoney.sslTip', { defaultValue: 'Your payment information is protected by SSL encryption' })}
                    </p>
                </div>

                <div className="bg-gray-800 rounded-lg p-6 border border-gray-700 relative">
                    {/* 关闭按钮 */}
                    <button
                        onClick={() => navigate(-1)}
                        className="absolute top-3 right-3 text-gray-400 hover:text-white transition-colors"
                        aria-label={t('PayMoney.close', { defaultValue: 'Close' })}
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                    <Elements stripe={stripePromise}>
                        <PaymentForm paymentData={paymentData} />
                    </Elements>
                </div>

                {/* 安全提示 */}
                <div className="mt-6 text-center">
                    <div className="flex items-center justify-center space-x-4 text-gray-400 text-sm">
                        <div className="flex items-center">
                            <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                <path fillRule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clipRule="evenodd" />
                            </svg>
                            {t('PayMoney.sslEncryption', { defaultValue: 'SSL Encryption' })}
                        </div>
                        <div className="flex items-center">
                            <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                <path fillRule="evenodd" d="M2.166 4.999A11.954 11.954 0 0010 1.944 11.954 11.954 0 0017.834 5c.11.65.166 1.32.166 2.001 0 5.225-3.34 9.67-8 11.317C5.34 16.67 2 12.225 2 7c0-.682.057-1.35.166-2.001zm11.541 3.708a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                            </svg>
                            {t('PayMoney.secureAuth', { defaultValue: 'Secure Authentication' })}
                        </div>
                        <div className="flex items-center">
                            <svg className="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                <path d="M4 4a2 2 0 00-2 2v1h16V6a2 2 0 00-2-2H4z" />
                                <path fillRule="evenodd" d="M18 9H2v5a2 2 0 002 2h12a2 2 0 002-2V9zM4 13a1 1 0 011-1h1a1 1 0 110 2H5a1 1 0 01-1-1zm5-1a1 1 0 100 2h1a1 1 0 100-2H9z" clipRule="evenodd" />
                            </svg>
                            {t('PayMoney.stripePayment', { defaultValue: 'Stripe Payment' })}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default PayMoney;